//
//  LoginServer.m
//  CYWFrame
//
//  Created by Macx on 2017/8/3.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "LoginServer.h"
#import "TabBarViewController.h"
#import "LookingPassViewController.h"
#import "JPUSHService.h"

#import <ShareSDK/ShareSDK.h>

@implementation LoginServer

+ (void)loginParam:(id)param {

	NetworkTool *manager = [NetworkTool sharedTool];
    [manager requestWithName:@"手机登录" URLString:APILoginMobile parameters:param method:@"POST" callBack:^(id responseObject) {
        
        NSDictionary *tokenDict = [responseObject valueForKey:@"data"];
        SetUserDefaule(tokenDict, Token);
		NSLog(@"user role is :%@", GetUserDefaule(Token)[@"role"]);
		
        [[NetworkTool sharedTool] requestWithName:@"获取用户信息" URLString:APIUser parameters:nil method:@"GET" callBack:^(id responseObject) {
			
            NSDictionary *userDict = [responseObject valueForKey:@"data"];
            SetUserDefaule(userDict, USERINFO);
			NSLog(@"user role is------ :%@", userDict);
			
			//reset 极光推送别名
			NSDictionary *userInfo = GetUserDefaule(USERINFO);
			if (userInfo != NULL) {
				[JPUSHService setAlias:userInfo[@"user_id"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
					NSLog(@"aliad %ld %@ %ld", iResCode, iAlias, seq);
				} seq:999];
			}
			
            // 几时保存持久化
//            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [self tcLogin:userDict isJ:1 isP:0];
            
        }];
    }];
}

+ (void)shareLoginWay:(NSString *)way {
    
    SSDKPlatformType type;
    
    //    NSDictionary *param;
    
    if ([way isEqualToString:@"qq"]) {
        type = SSDKPlatformTypeQQ;
        //        param = @{SSDKAuthSettingKeyScopes:[NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO, kOPEN_PERMISSION_GET_USER_INFO, kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil]};
    }
    else {
        type = SSDKPlatformTypeWechat;
        
    }
    
    
    [ShareSDK getUserInfo:type onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
         [ShareSDK cancelAuthorize:type];
        //    [ShareSDK authorize:type settings:@{SSDKAuthSettingKeyScopes:@[@"snsapi_userinfo"]} onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        if (state == SSDKResponseStateSuccess) {
            
            NSString *s;
            if (user.gender == 2) {
                s = @"2";
            }
            else
                s = @"1";
            
            NSLog(@"share login success ， user = %@", user);
            NSDictionary * doc = user.rawData;
            
            NSString *unionid;
            if ([way isEqualToString:@"qq"]) {
                unionid = @"";
                
                
                NSString *url = [NSString stringWithFormat:@"https://graph.qq.com/oauth2.0/me?access_token=%@&unionid=1", user.credential.token];
                
                AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
                
                [afn GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSLog(@"获取qq unionid 成功 %@", responseObject);
                    NSDictionary *param = @{@"openid":user.uid,
                                            @"source":way,
                                            @"nickname":user.nickname,
                                            @"sex":s,
                                            @"avatar":user.icon,
                                            @"unionid":@""}; // 不知道会不会有问题
                    [self getUserWay:way param:param];
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
                    NSLog(@"data = %@", errorData);
                    NSString *aStr = [[NSString alloc] initWithData:errorData encoding:NSASCIIStringEncoding];
                    
                    NSLog(@" s %@", aStr);
                    NSString *s2 = [[aStr componentsSeparatedByString:@"("][1] componentsSeparatedByString:@")"][0];
                    NSLog(@" s2 %@", s2);
                    
                    NSDictionary *ddd = [NSString dictionaryWithJsonString:s2];
                    NSLog(@"d %@", ddd);
                    
                    NSDictionary *param = @{@"openid":user.uid,
                                            @"source":way,
                                            @"nickname":user.nickname,
                                            @"sex":s,
                                            @"avatar":user.icon,
                                            @"unionid":ddd[@"unionid"]};
                    [self getUserWay:way param:param];
                }];
                
                
            }
            else {
                NSDictionary * doc = user.rawData;
                unionid = [doc objectForKey:@"unionid"];
                NSDictionary *param = @{@"openid":user.uid,
                                        @"source":way,
                                        @"nickname":user.nickname,
                                        @"sex":s,
                                        @"avatar":user.icon,
                                        @"unionid":unionid};
                
                [self getUserWay:way param:param];
            }
        }
        else
        NSLog(@"%@ 第三方登录失败 = %@", way, error);
    }];
    
}

+ (void)getUserWay:(NSString *)way param:(NSDictionary *)param {
    
    [[NetworkTool sharedTool] requestWithName:[NSString stringWithFormat:@"%@ 登录", way] URLString:APISocialUserSessions parameters:param method:@"POST" callBack:^(id responseObject) {
        
        SetUserDefaule([responseObject valueForKey:@"data"], Token);
        
        NSInteger p = [[responseObject valueForKey:@"data"][@"is_new"] integerValue];
        NSLog(@"ppp = %ld", p);
        [[NetworkTool sharedTool] requestWithName:@"获取用户信息" URLString:APIUser parameters:nil method:@"GET" callBack:^(id responseObject) {
            
            NSDictionary *userDict = [responseObject valueForKey:@"data"];
            SetUserDefaule(userDict, USERINFO);
			
			//重新reset极光推送的别名
			NSDictionary *userInfo = GetUserDefaule(USERINFO);
			if (userInfo != NULL) {
				[JPUSHService setAlias:userInfo[@"user_id"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
					NSLog(@"aliad %ld %@ %ld", iResCode, iAlias, seq);
				} seq:999];
			}
            [self tcLogin:userDict isJ:1 isP:p];
        }];
        
    }];
    
}

+ (void)tcLogin:(NSDictionary *)userInfo isJ:(NSInteger)isJ isP:(NSInteger)isP {
    
    UIViewController *currVC = [((AppDelegate *)[UIApplication sharedApplication].delegate) topViewController];
	
    TCLoginParam *_loginParam;
    
    // 先判断是否自动登录
    BOOL isAutoLogin = [TCLoginModel isAutoLogin];
    if (isAutoLogin) {
        _loginParam = [TCLoginParam loadFromLocal];
    }
    else {
        _loginParam = [[TCLoginParam alloc] init];
    }
    // 登录前需要先初始化IMSDK
    [[TCLoginModel sharedInstance] initIMSDK];
    
    // 腾讯方法，传入三个参数
    _loginParam.identifier = [userInfo valueForKey:@"user_id"]; // 用户名
    _loginParam.userSig = [userInfo valueForKey:@"im_sig"]; // im 的 token
    _loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];
    
    [[TCLoginModel sharedInstance] login:_loginParam succ:^{
        
//        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"login"];
        
        // 登录 IM 成功 单例保存自动登录参数
        NSLog(@"loginIMSDK success");
        
        //创建通知
        NSNotification *notification =[NSNotification notificationWithName:@"c2cNotification" object:nil userInfo:nil];
        //通过通知中心发送通知
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        
        // 持久化param
        // 这个是腾讯的，我本地有必要save吗？
        //[_loginParam saveToLocal];
        
        [IMAPlatform configWith:_loginParam.config];
        [[IMAPlatform sharedInstance] configOnLoginSucc:_loginParam];
		
		[MBProgressHUD hideHUDForView:currVC.view animated:YES];
        // 当前window 改为 tabbar
        if (isJ == 1) {
            if (isP == 1) { // 跳到手机绑定
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                LookingPassViewController *looKVC = [[LookingPassViewController alloc] init];
                looKVC.one = 1;
                looKVC.type = @"binding";
                
                UINavigationController *nav = [[UINavigationController alloc]  initWithRootViewController:looKVC];
                [nav.navigationBar setTranslucent:NO];
                // 设置导航栏背景颜色
                nav.navigationBar.barTintColor = [UIColor colorWithHexString:UIMainColor alpha:1.0];
                // 设置导航栏字体颜色
                [nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
                
                app.window.rootViewController = nav;
            }
            else {
                AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                app.window.rootViewController = [[TabBarViewController alloc] init];
            }
        }
        
    } fail:^(int code, NSString *msg) {
        NSLog(@"loginIMSDK fail");
        [currVC presentViewController:[LZCTools alertMessage:@"登录失败，请重新登录"] animated:YES completion:nil];
    }];
    
}

@end
